package main

import (
	"context"
	"fmt"
	"time"
)

func test(ctx context.Context, ch chan byte) {
	defer func() {
		fmt.Println("go route is done!!!")
	}()

	fmt.Println("go route is start!")

	for {
		select {
		case <-ctx.Done():
			fmt.Println("receive cancel!")
			return
		case v := <-ch:
			fmt.Println("read chan value = ", v)
		}
		fmt.Println("aaa")
	}
}

func main() {
	ctx, cancel := context.WithCancel(context.Background())
	ch := make(chan byte, 100)
	go test(ctx, ch)
	for i := 1; i <= 3; i++ {
		ch <- byte(i)
	}
	time.Sleep(time.Second * 5)
	fmt.Println("do cancel")
	cancel()
	time.Sleep(time.Second)
	fmt.Println("main is done!")

	ctx, cancel = context.WithTimeout(context.Background(), time.Second*3)
	go test(ctx, ch)
	for i := 1; i <= 5; i++ {
		ch <- byte(i)
		time.Sleep(time.Second)
	}
	cancel()
	time.Sleep(time.Second)
	fmt.Println("main is done2!")
	bits := []byte{1, 2, 3, 4, 5}
	var nums []interface{}
	for _, v := range bits {
		nums = append(nums, v)
	}
	fmt.Println(bits)
	fmt.Println(nums...)
}
